package com.chenglu.android.common.net.exception;

import android.accounts.NetworkErrorException;

import com.chenglu.android.common.base.BaseView;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.rxjava3.annotations.NonNull;

/**
 * * @author: lyj
 *  @Created: by Copyright 2023/3/6 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * Describe：网络请求异常类
 *
 */
public class NetErrorException extends Exception {

    /**
     * 网络请求错误码
     */
    private String errorCode;
    /**
     * 响应的Data
     */
    private String responseData;

    public NetErrorException() {
    }

    public NetErrorException(String message) {
        this("", message);
    }

    public NetErrorException(String errorCode, String message) {
        this(errorCode, message, "");

    }

    public NetErrorException(String errorCode, String message, String responseData) {
        super(message);
        this.errorCode = errorCode;
        this.responseData = responseData;
    }

    /**
     * 返回网络请求错误码
     *
     * @return errorCode
     */
    public String getNetErrorCode() {
        return errorCode;
    }

    /**
     * 返回网路响应的DATA
     *
     * @return responseData
     */
    public String getNetResponseData() {
        return responseData;
    }


    public  static void apiError(@NonNull Throwable e, BaseView baseView) {

        if (e instanceof ConnectException || e instanceof NetworkErrorException || e instanceof UnknownHostException) {
             ToastUtils.show("网络不可用，请检查您的网络状态！");
             baseView.onNetWorkError(e.getMessage());
        } else if (e instanceof TimeoutException || e instanceof SocketTimeoutException) {
             baseView.onNetOutTimeError(e.getMessage());
            ToastUtils.show("请求超时！");
        } else {
            //401 登录异常
            if(e.getMessage().contains("401")){
                ToastUtils.show("登录失效，请重新登录");
                baseView.onError(e.getMessage());
            }else if(e.getMessage().contains("HTTP")){
                baseView.onEmpty(e.getMessage());
                ToastUtils.show("系统维护中，请稍等！");
            }else {
                LogUtils.e("异常情况-"+ e.getMessage());
                ToastUtils.show("异常捕获，请稍等！");
            }


        }

    }
}
